
#include "HttpServer.hpp"

#include <memory>

using namespace Server;

static void Usage(string argv)
{
    cerr << "Usage: \n\t" << argv <<" port \n\n" << endl;
}
string suffixToDesc(const string suffix)
{
    string ct = "Content-Type: ";
    if(suffix == ".html") { ct += "text/html"; }
    else if(suffix == ".jpg") { ct += "application/x-jpg"; }
    ct += "\r\n";
    return ct;
}
// 1. 服务器和网页分离 html
// 2. url->  /: web根目录
// 3. 要正确的给客户端返回资源，首先要自己知道 -> 所有的资源都有后缀
bool Get(const HttpRequest& req, HttpResponse& resp)
{
    cout<< "----------------------http start------------------------------------" << endl;
    cout << req.inbuffer << endl;   //请求
    cout << "method: " << req.method << endl; 
    cout << "url: " << req.url << endl; 
    cout << "httpversion: " << req.httpversion << endl; 
    cout << "path: " << req.path << endl; 
    cout << "suffix: " << req.suffix << endl; 
    cout << "size: " << req.size << "字节" << endl; 
    cout<< "----------------------http end------------------------------------" << endl;

    //响应
    string body;
    // body.reserve(req.size+1);
    if(!Util::readFile(req.path,&body))
    {
        Util::readFile(html_404,&body); 
    }

    string respline = "Http/1.1 200 OK\r\n";
    string respheader = suffixToDesc(req.suffix);
    if(req.size > 0)
    {
        respheader += "Content-Length: ";
        respheader += to_string(body.size());
        respheader += "\r\n";
    }
    string respblank = "\r\n";
    // string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>你好呀</p></body></html>";

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    resp.outbuffer += body;

    return true;
}
// ./httpserver 8080
int main(int argc,char* argv[])
{

    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<HttpServer> httpsvr(new HttpServer(Get,port));
    httpsvr->initServer();
    httpsvr->start();


    return 0;
}